#include "qdriverlisternwidget.h"

#include "qdrivertabview.h"
#include "qdriverdatawidget.h"

#include "../../libs/core/qsoftcore.h"
#include "../../libs/device/qdevicemanager.h"
#include "../../libs/device/driver_listern/qserverdriverlistern.h"
#include "../../libs/device/qbasedefine.h"
#include "../../libs/shared/xmlobject.h"

#include <QVBoxLayout>

QDriverListernWidget::QDriverListernWidget(tagDeviceInfo* info,QWidget *parent) :
    QWidget(parent),
    m_device_info(info),
    m_tab_bar(new QDriverTabView),
    m_stacked_widget(new QStackedWidget)
{
    m_device_manager=QSoftCore::get_core()->get_device_manager();

    m_driver_listern=m_device_manager->start_driver_listern(info->m_uuid);

    connect(m_driver_listern,SIGNAL(update_driver_signals()),this,SLOT(update_driver()));
    connect(m_tab_bar,SIGNAL(current_index_changed(int)),m_stacked_widget,SLOT(setCurrentIndex(int)));
    connect(m_driver_listern,SIGNAL(add_data_signals(QString)),this,SLOT(add_message(QString)));
    QVBoxLayout *v=new QVBoxLayout;

    v->setMargin(0);
    v->setSpacing(0);

    v->addWidget(m_tab_bar);
    v->addWidget(m_stacked_widget);

    setLayout(v);

    update_driver();
}

void QDriverListernWidget::update_driver()
{
    m_tab_bar->clear();
    QList<QDriverDataWidget*> l=m_widgets.values();
    while(l.size()>0)
    {
        QWidget* wid=l.takeFirst();
        m_stacked_widget->removeWidget(wid);
        delete wid;
    }

    QList<QDriverInfo>  list=m_driver_listern->get_drivers();
    foreach(QDriverInfo info,list)
    {
        QDriverDataWidget *wid=new QDriverDataWidget;
        m_stacked_widget->addWidget(wid);
        m_tab_bar->insert_data(info.m_propertys.at(0).m_value);
        wid->set_property(info);
        m_widgets.insert(info.m_uuid,wid);
    }
    if(list.size()>0)
    {
        m_tab_bar->set_current_index(0);
    }
}

void QDriverListernWidget::add_message(const QString &data)
{
    XMLObject xml;

    if(!xml.load(data,0))
    {
        return;
    }

    QDriverDataWidget *wid=m_widgets.value(xml.get_property("driver_uuid"));
    if(wid!=NULL)
    {
        wid->add_data(&xml);
    }
}
